# Define variables
CRST_ID="CAPAR_REMIT_TO_ADDRESS"
PROG_PATH="../ctl"
LOG_PATH="../log"
DATA_BASE="../data"

FILE_TIME=`date +"%Y%m%d%H%M%S"`
DATA_PATH=${DATA_BASE}
CTL_FILE_NAME=${CRST_ID}".ctl"
OUT_FILE_NAME=${CRST_ID}".ldr.out."${FILE_TIME}
BAD_FILE_NAME=${CRST_ID}".ldr.bad."${FILE_TIME}
LOG_FILE_NAME=${CRST_ID}".ldr.log."${FILE_TIME}
DATA_FILE_NAME="${DATA_PATH}/CAPAR_REMIT_TO_ADDRESS.dat"
LOGIN=$1

echo ${LOG_PATH}/${OUT_FILE_NAME}

# Test that the $LOGIN variable has been set
if [ ${LOGIN:-0} = 0 ]; then
	echo "Oracle username and password must be entered"
	exit 1
fi

# add sqlplus ..... delete
# sqlplus -s ${LOGIN} @CAPAR_REMIT_TO_ADDRESS.sql

# Load data into Oracle database
sqlldr ${LOGIN} \
data=${DATA_FILE_NAME} \
control=${PROG_PATH}/${CTL_FILE_NAME} \
bad=${LOG_PATH}/${BAD_FILE_NAME} \
log=${LOG_PATH}/${LOG_FILE_NAME} > ${LOG_PATH}/${OUT_FILE_NAME}

# Test the for the existence of a bad file
cvresult=`find ${LOG_PATH} -name ${BAD_FILE_NAME} -print`

# Test to see if a download file was created and is available
if [ "${cvresult:-0}" = 0 ]; then
	# Check to see if there was an Oracle error message in the log file
	cvresult=`grep -iw 'error' $LOG_PATH/${LOG_FILE_NAME}`
	if [ "${cvresult:-0}" = 0 ]; then
		echo "Successful completion"
		exit 0
	else
		echo "The SQL*Load did not finish successfully"
		echo "The Oracle error message was : "${cvresult}
		exit 1
	fi
else
	# The BAD file must exist, therefore there were errors with SQL*Loader
	echo "Error during SQL*Load, please refer to the LOG and BAD files for more details"
	exit 1
fi

